import React, { Component } from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom'
import Main from '../main';
import fetch from '../../util/fetch'
import {getQueryVariable, removeToken, removeIdentity} from "../../util/public";
import '../../util/ipConfig'
import md5 from "md5";
import Detail from "../detail";
import IframePage from "../iframePage"
import { Button, Space, ConfigProvider, message } from 'antd';
// 由于 antd 组件的默认文案是英文，所以需要修改为中文
import zh_CN from 'antd/lib/locale-provider/zh_CN';
import moment from 'moment';
import 'moment/locale/zh-cn';
import "lancoo-web-ui/dist/style.css";

moment.locale('zh-cn');
class App extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            loading: true,
         }
    }
    //获取公共信息数据
    getCommonData = () => {
      if(!getQueryVariable("lg_tk") && !sessionStorage.getItem("token")){
        return;
      }
      console.log("lg_ic", getQueryVariable("lg_ic"));
      sessionStorage.setItem("token", getQueryVariable("lg_tk"));
      sessionStorage.setItem("identityCode", getQueryVariable("lg_ic"))
      let token = getQueryVariable("lg_tk");

      this.getSysInfo()
      this.getSysAddrInfo()
      
      //获取用户信息
      let url = window.BasicProxy + "/api/commons/users?token=" + token;
      fetch
      .get({url})
      .then((res)=>res.json())
      .then((res)=>{
        if(res.code == 200){
          let data = res.data[0];
          let lgic = getQueryVariable("lg_ic")
          if(lgic && data.identityList){
            data.identityList.forEach(item => {
              if(item.identityCode === lgic){
                data.identityImg = item.iconUrl
                data.identityName = item.identityName
                data.isPreset = item.isPreset
              }
            })
          }
          data.identityInfos = data.identityList
          sessionStorage.setItem("userInfo", JSON.stringify(data));
          sessionStorage.setItem("userId", data.userId);
          sessionStorage.setItem("userName", data.userName);
          sessionStorage.setItem("imageUrl", data.identityImg);
          sessionStorage.setItem("productUseRange", data.productUseRange);

          // 锁校验
          fetch.get({
            url: window.BasicProxy + '/api/commons/locker/check',
          }).then(res => res.json()).then(res => {
              if(res.code == 200){
                  if(res.data.Result != 1){
                    window.open(res.data.lockerErrAddr + res.data.Result, "_self")
                  }else{
                    this.setState({
                      loading: false,
                    })
                  }
              }
          })

          this.getNotice()
        }
      })
    }
    // 获取系统信息
    getSysInfo = () => {
      fetch
      .get({ url: window.BasicProxy + "/api/commons/system/info" })
      .then((res)=>res.json())
      .then((res)=>{
        if(res.code == 200){
          let data = res.data;
          sessionStorage.setItem("sysInfo", JSON.stringify(data));
          sessionStorage.setItem("eduId", data.eduId);
          sessionStorage.setItem("eduName", data.eduName);
          sessionStorage.setItem("sysId", data.sysId);
          sessionStorage.setItem("baseUrl", data.baseUrl);

          this.getSkinInfo()
        }
      })
    }
    // 获取其他系统地址
    getSysAddrInfo = () => {
      fetch
      .get({
        url: window.BasicProxy + "/api/commons/system/server/info",
        params: {
          sysIds: "U10,264,211"
        }
      })
      .then((res)=>res.json())
      .then((res)=>{
        if(res.code == 200){
          let obj = {}
          res.data.forEach(item => {
            if(!item.sysId){
              return
            }
            if(item.sysId === "264"){
              sessionStorage.setItem("officeUrl", item.webSvrAddr)
            }
            if(item.sysId === "211"){
              sessionStorage.setItem("noticeUrl", item.webSvrAddr)
            }
            obj[item.sysId] = item.webSvrAddr
          })
          sessionStorage.setItem("sysAddrInfo", JSON.stringify(obj));
        }
      })
    }
    // 引入消息中心
    getNotice = () => {
      let webBaseUrl = sessionStorage.getItem("baseUrl");
      let token = sessionStorage.getItem("token");
      let sysId = 211;
      // let mdTokenSysId = md5(sysId)
      // 	.split("")
      // 	.reverse()
      //   .join("");
      let mdTokenSysId = 'eb163727917cbba1eea208541a643e74'.split("").reverse().join("")
      fetch
        .get({
          url: webBaseUrl + "/BaseApi/Global/GetSubSystemsMainServerBySubjectID",
          params: {
            appid: sysId,
            access_token: mdTokenSysId,
            sysIDs: sysId
          }
        })
        .then(res => res.json())
        .then(res => {
          if (res.StatusCode == 200 && res.Data) {
            let WebSvrAddr = res.Data[0].WebSvrAddr;
            let WsSvrAddr = res.Data[0].WsSvrAddr;
            sessionStorage.setItem("PsnMgrToken", token); //用户 Token
            sessionStorage.setItem("PsnMgrMainServerAddr", webBaseUrl); //基础平台 IP 地址和端口号
            sessionStorage.setItem("PsnMgrLgAssistantAddr", WebSvrAddr); //个人信息管理系统 Web 站点 IP 地址和端口号

            // 引入js和css，要顺序引入
            this.loadScriptOrCss([
              `${WebSvrAddr}/PsnMgr/LgAssistant/js/jquery-1.7.2.min.js`,
              `${WebSvrAddr}/PsnMgr/LgAssistant/assets/jquery.pagination.js`,
              `${WebSvrAddr}/PsnMgr/LgAssistant/js/lancoo.cp.assistantInfoCenter.js`,
              `${WebSvrAddr}/PsnMgr/LgAssistant/css/lancoo.cp.assistantInfoCenter.css`,
            ]);
            
          }
        });
    };
    // 同步引入动态js和css函数
    loadScriptOrCss = (urlArr, num) => {
      if (!num) {
        num = 0;
      }
      let that = this
      //正则判断是否是css;
      var reg = RegExp(/.css/);
  
      if (reg.test(urlArr[num])) {
        // 动态生成css
        var scriptOrCss = document.createElement('link');
        scriptOrCss.type = 'text/css';
        scriptOrCss.async = 'async';
        scriptOrCss.href = urlArr[num];
        scriptOrCss.rel = "stylesheet";
        document.getElementsByTagName("head")[0].appendChild(scriptOrCss);
  
      } else {
        // 动态生成js
        var scriptOrCss = document.createElement('script');
        scriptOrCss.type = 'text/javascript';
        scriptOrCss.async = 'async';
        scriptOrCss.src = urlArr[num];
        document.body.appendChild(scriptOrCss);
      }
      if (scriptOrCss.readyState) {
        //IE下
        scriptOrCss.onreadystatechange = function () {
          if (scriptOrCss.readyState == 'complete' || scriptOrCss.readyState == 'loaded') {
            scriptOrCss.onreadystatechange = null;
            num++;
            if (num == urlArr.length) {
              sessionStorage.setItem('PsnMgrLooding', 1);
              return;
            } else {
              that.loadScriptOrCss(urlArr, num);
            }
          }
        }
      } else {
        //其他浏览器
        scriptOrCss.onload = function () {
          num++;
          if (num == urlArr.length) {
            sessionStorage.setItem('PsnMgrLooding', 1);
            return;
          } else {
            that.loadScriptOrCss(urlArr, num);
          }
        }
      }
    }
    // 获取皮肤信息
    getSkinInfo = () => {
      let baseUrl = sessionStorage.getItem("baseUrl");
      let token = sessionStorage.getItem("token");
      let obj = {
        appid: "231",
        token,
      };
      let skin = 1
      fetch
        .get({
          url: baseUrl + "openapi/v1/system/facade/getSkin",
          params: obj,
          advance: false,
        })
        .then((res) => res.json())
        .then((res) => {
          if (res.ErrCode == 0) {
            skin = res.Data.skin
          }
        })
        .finally(() => {
          document.body.classList.add(`lg-skin-s${skin}`);
        });
    };
    componentDidMount(){
        this.getCommonData();
    }
    render() {  
        let dom = this.state.loading ? (<Button 
            style={{
                position: 'fixed',
                top: 0,
                left: 0,
                zIndex: 999,
                width: '100vw',
                height: '100vh',
                opacity: .75,
            }}
            loading='loading'
            >
                loading
            </Button>) : (<Switch>
                        <Route path="/" exact component={Main} />
                        <Route path="/noticeDetail" component={Detail} />
                        <Route path="/iframeSchoolNotice" component={IframePage} />
                    </Switch>)
        return ( <div>
            <ConfigProvider locale={zh_CN}>
                <Router>
                    {
                        dom
                    }
                    
                </Router>
            </ConfigProvider>
        </div> );
    }
}
 
export default App;